﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _2_12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private double GetPacket(ref double total, int n)
        {
            if (n == 1) return total; // 最后一个红包：剩余全部金额
            Random rnd = new Random();
            double avg = Math.Round(total / n, 2); // 剩余金额平均值（精确到分）
                                                   // 红包金额范围：0.5*avg ~ 1.5*avg（实验提示核心）
            double thisPacket = avg / 2 + avg * rnd.Next(101) / 100;
            thisPacket = Math.Round(thisPacket, 2); // 精确到分
            total -= thisPacket;
            total = Math.Round(total, 2); // 更新剩余金额
            return thisPacket;
        }
        private double SumPacket(double[] redPacket)
        {
            double sum = 0;
            foreach (double p in redPacket)
            {
                sum += p;
            }
            return Math.Round(sum, 2); // 精确到分
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                double total = double.Parse(textBox1.Text);
                int n = int.Parse(textBox2.Text);
                double[] redPacket = new double[n];

                // 循环生成每个红包
                for (int i = n; i > 0; i--)
                {
                    redPacket[n - i] = GetPacket(ref total, i);
                }

                // 显示结果和校验总和
                textBox3.Text = string.Join("\t", redPacket);
                textBox4.Text = SumPacket(redPacket).ToString();
            }
            catch (FormatException)
            {
                MessageBox.Show("请输入有效数字！");
            }
        }
    }
}
